package com.newasia.management.services;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.newasia.commons.tool.exception.ValidateException;
import com.newasia.management.ISysUserService;
import com.newasia.management.constants.ManagementRetCode;
import com.newasia.management.converter.SysRoleConverter;
import com.newasia.management.converter.SysUserConverter;
import com.newasia.management.dal.user.entitys.*;
import com.newasia.management.dal.user.persistence.SysRoleMapper;
import com.newasia.management.dal.user.persistence.SysUserMapper;
import com.newasia.management.dal.user.persistence.SysUserRoleMapper;
import com.newasia.management.dto.user.SysUserDto;
import com.newasia.management.dto.user.UserRoleListDto;
import com.newasia.management.dto.user.login.*;
import com.newasia.management.dto.user.user.*;
import com.newasia.management.utils.ExceptionProcessorUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.CollectionUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class SysUserServiceImpl implements ISysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysRoleMapper sysRoleMapper;

    @Autowired
    SysUserConverter sysUserConverter;

    @Autowired
    SysRoleConverter sysRoleConverter;

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Override
    public SysUserLoginResponse selectUserByName(SysUserLoginRequest request) {
        log.info("Begin UserLoginServiceImpl.selectUserByName: userName:"+request.getUserName());
        SysUserLoginResponse response = new SysUserLoginResponse();
        try{
            SysUser sysUser=sysUserMapper.selectUserByName(request.getUserName());
            if(sysUser==null){
                return null;
            }
            response=sysUserConverter.user2Res(sysUser);
        }catch (Exception e){
            log.error("SysUserServiceImpl.selectUserByName Occur Exception :"+e);
            response.setCode(ManagementRetCode.SYSTEM_ERROR.getCode());
            response.setMsg(ManagementRetCode.SYSTEM_ERROR.getMessage());
        }
        return response;
    }

    @Override
    @Transactional
    public SysUserRegisterResponse register(SysUserRegisterRequest request) {
        log.info("Begin UserLoginServiceImpl.register: request:"+request);
        SysUserRegisterResponse response=new SysUserRegisterResponse();
        try {
            validUserRegisterRequest(request);
            SysUser user = new SysUser();
            user.setUserName(request.getUserName());
            user.setPassword(request.getUserPwd());
            user.setSalt(request.getSalt());
            user.setState("NORMAL");
            user.setCreatedTime(new Date());
            user.setCompanyName(request.getCompanyName());
            user.setFile(request.getFile());
            user.setEmail(request.getEmail());
            user.setMobile(request.getMobile());
            if(sysRoleMapper.selectByPrimaryKey(request.getRoleId())==null){
                response.setCode(ManagementRetCode.ROLE_NOT_EXIST.getCode());
                response.setMsg(ManagementRetCode.ROLE_NOT_EXIST.getMessage());
                return response;
            }
            if(sysUserMapper.insertSelective(user)!=1){
                response.setCode(ManagementRetCode.USER_REGISTER_FAILED.getCode());
                response.setMsg(ManagementRetCode.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            Long userId = sysUserMapper.selectUserIdByName(request.getUserName());
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(request.getRoleId());
            sysUserRole.setUserId(userId);
            if(sysUserRoleMapper.insertSelective(sysUserRole)!=1){
                response.setCode(ManagementRetCode.ROLE_COMMENT_FAILED.getCode());
                response.setMsg(ManagementRetCode.ROLE_COMMENT_FAILED.getMessage());
                return response;
            }
            response.setCode(ManagementRetCode.SUCCESS.getCode());
            response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("SysUserLoginServiceImpl.register Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
        }
        return response;
    }

    @Override
    @Transactional
    public SysUserUpdateResponse updateUser(SysUserUpdateRequest request) {
        log.info("Begin UserLoginServiceImpl.updateUser: request:"+request);
        SysUserUpdateResponse response=new SysUserUpdateResponse();
        try {
            SysUser user = new SysUser();;
            user.setUserName(request.getUserName());
            user.setUserId(request.getUserId());
            user.setPassword(request.getUserPwd());
            user.setSalt(request.getSalt());
            user.setState(request.getState());
            user.setCompanyName(request.getCompanyName());
            user.setFile(request.getFile());
            user.setEmail(request.getEmail());
            user.setMobile(request.getMobile());
            user.setUpdatedTime(new Date());

            if(sysUserMapper.updateByPrimaryKeySelective(user)!=1){
                response.setCode(ManagementRetCode.USER_UPDATE_FAILED.getCode());
                response.setMsg(ManagementRetCode.USER_UPDATE_FAILED.getMessage());
                return response;
            }

            if(request.getRoleId()!=null&&!"".equals(request.getRoleId())){
                SysUserRole sysUserRole = sysUserRoleMapper.selectUserByUserId(request.getUserId());
                sysUserRole.setRoleId(request.getRoleId());
                sysUserRole.setUserId(request.getUserId());
                if(sysUserRoleMapper.updateByPrimaryKey(sysUserRole)!=1){
                    response.setCode(ManagementRetCode.ROLE_COMMENT_FAILED.getCode());
                    response.setMsg(ManagementRetCode.ROLE_COMMENT_FAILED.getMessage());
                    return response;
                }
            }
            response.setCode(ManagementRetCode.SUCCESS.getCode());
            response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("SysUserLoginServiceImpl.updateUser Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
        }
        return response;
    }

    @Override
    public SysUserListResponse selectSysUserList(SysUserListRequset request) {
        log.info("Begin SysRoleServiceImpl.selectSysUserList: request:"+request);
        SysUserListResponse response = new SysUserListResponse();
        response.setCode(ManagementRetCode.SUCCESS.getCode());
        response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        try{
            request.requestCheck();
            PageHelper.startPage(request.getPage(),request.getSize());
            List<UserAndRole> users = sysUserMapper.selectUserByRoleId(request.getRoleId(),request.getUserName());
            if(CollectionUtils.isEmpty(users)){
                response.setTotal(0L);
                response.setSysUserDtoList(new ArrayList<>());
                return response;
            }
            //List<UserRoleListDto> infos = new ArrayList<>();
            PageInfo<UserAndRole> pageInfo=new PageInfo<>(users);
            response.setTotal(pageInfo.getTotal());
            List<UserRoleListDto> dtos = sysUserConverter.userRole2Dto(users);
            response.setSysUserDtoList(dtos);
        }catch (Exception e){
            log.error("SysRoleServiceImpl.selectSysUserList Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
            e.printStackTrace();
        }
        return response;
    }

    @Override
    public DeleteSysUserResponse deleteSysUser(DeleteSysUserRequset request) {
        log.info("Begin UserLoginServiceImpl.deleteSysUser: request:"+request);
        DeleteSysUserResponse response=new DeleteSysUserResponse();
        try {
            SysUser user = sysUserMapper.selectByPrimaryKey(request.getUserId());
            user.setState("PROHIBIT");
            user.setUpdatedTime(new Date());

            if(sysUserMapper.updateByPrimaryKey(user)!=1){
                response.setCode(ManagementRetCode.USER_REGISTER_FAILED.getCode());
                response.setMsg(ManagementRetCode.USER_REGISTER_FAILED.getMessage());
                return response;
            }
            response.setCode(ManagementRetCode.SUCCESS.getCode());
            response.setMsg(ManagementRetCode.SUCCESS.getMessage());
        }catch (Exception e){
            log.error("SysUserLoginServiceImpl.register Occur Exception :"+e);
            ExceptionProcessorUtils.wrapperHandlerException(response,e);
        }
        return response;
    }

    //校验参数以及校验用户名是否存在
    private void validUserRegisterRequest(SysUserRegisterRequest request){
        request.requestCheck();
        Long userId = sysUserMapper.selectUserIdByName(request.getUserName());
        if(userId!=null&&!"".equals(userId)){
            throw new ValidateException(
                    ManagementRetCode.USERNAME_ALREADY_EXISTS.getCode(),
                    ManagementRetCode.USERNAME_ALREADY_EXISTS.getMessage());
        }
    }
}
